package com.order.flowserver.domain.config;

import java.sql.Driver;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.transaction.support.TransactionTemplate;

import com.shitou.server.data.db.MyBatisMapper;
import com.shitou.server.mybatis.MysqlPageReqParamInterceptor;
import com.shitou.server.mybatis.MysqlPageResultInterceptor;

/**
 * <br>
 *
 * @author 李恒
 * @version 1.0
 * @date: 2016/10/11 0011 下午 5:48
 */
@Configuration
@MapperScan(basePackages = "com.order.flowserver.domain.dataaccess", annotationClass = MyBatisMapper.class)
public class DataSourceConfig {
    private String url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE";
    private String username = "sa";
    private String password = "";
    private Driver driver = new org.h2.Driver();

    @Bean
    public DataSource dataSource() {
        return new SimpleDriverDataSource(driver, url, username, password);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        Resource[] mappers = (new PathMatchingResourcePatternResolver()).getResources("classpath*:mybatis_mapper/*Mapper.xml");
        sessionFactory.setMapperLocations(mappers);
        sessionFactory.setPlugins(new Interceptor[]{new MysqlPageReqParamInterceptor(),new MysqlPageResultInterceptor()});
        return sessionFactory.getObject();
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        final DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

    @Bean
    public TransactionTemplate transactionTemplate(@Qualifier("dataSourceTransactionManager") DataSourceTransactionManager dataSourceTransactionManager) throws Exception {
        final TransactionTemplate jdbcTemplate = new TransactionTemplate();
        jdbcTemplate.setTransactionManager(dataSourceTransactionManager);
        return jdbcTemplate;
    }
}